package com.loveyukari.service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.loveyukari.dao.AuthOldNameDao;
import com.loveyukari.dao.PermissionDao;
import com.loveyukari.utils.HttpUtils;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.loveyukari.dao.AuthDao;
import com.loveyukari.model.Auth;

import net.sf.json.JSONObject;

/**
*
*yangshaohua
*2017年2月13日下午6:14:23
**/
@Service
public class AuthService {
	
	@Autowired
	private AuthDao authDao;
	@Autowired
    private AuthOldNameDao authOldNameDao;
	@Autowired
	private PermissionDao permissionDao;

	private Logger log = LoggerFactory.getLogger(AuthService.class);
	
	@Autowired
	private RedisService redisService;

	private static final String AUTH_KEY = "auth:v3:";
	private static final String AUTH_TALK_KEY= "auth:talk:";


	public List<JSONObject> getAuthYubaFollow(int authId){
		ArrayList<JSONObject> resultList = new ArrayList<JSONObject>();
		try {
			int page = 1;
			while(true){
                HashMap<String, Object> param = new HashMap<>();
                param.put("uid",authId);
                param.put("limit",30);
                param.put("source",2);
                param.put("page",page);
                String result = HttpUtils.sendGet("https://yuba.douyu.com/wbapi/web/group/userFollow", param);
                JSONObject json = JSONObject.fromObject(result);
                JSONObject data = json.optJSONObject("data");
                JSONArray array = data.optJSONArray("list");
                for (int i = 0; i < array.size(); i++) {
                    JSONObject authYubaFollow = array.getJSONObject(i);
                    JSONObject j = new JSONObject();
                    j.put("groupId",authYubaFollow.optInt("group_id"));
                    j.put("groupName",authYubaFollow.optString("group_name"));
                    resultList.add(j);
                }
                page++;
                if (data.optInt("count_page") < page){
                    break;
                }
            }
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return resultList;
	}


	public List<JSONObject> getAuthFollow(int authId){
		String url = "https://mapi-yuba.douyu.com/wb/v3/user/followList";
		HashMap<String, String> headers = new HashMap<>();
		headers.put("client","ios");
		HashMap<String, Object> params = new HashMap<>();
		params.put("uid",authId);
		params.put("limit",20);
		ArrayList<JSONObject> list = new ArrayList<>();
		try {
			int page = 1;
			while(true){
                params.put("page",page++);
                String result = HttpUtils.sendGet(url, params, headers);
                JSONObject resultJson = JSONObject.fromObject(result);
                JSONObject data = resultJson.optJSONObject("data");
                JSONArray follows = data.optJSONArray("user_list");
                for (int i = 0; i < follows.size(); i++) {
                    JSONObject follow = follows.getJSONObject(i);
					JSONObject json = new JSONObject();
					json.put("id",follow.optInt("uid"));
					json.put("name",follow.optString("nickname"));
                    list.add(json);
                }
                if (follows.size() < 20){
                	break;
				}
            }
		} catch (Exception e) {
			log.error("关注获取失败: "+e.getMessage(),e);
		}
		return list;
	}

	public List<JSONObject> getAuthBadge(int authId){
		String url = "https://mapi-yuba.douyu.com/wb/v3/user/info/aggregation?user_id="+authId;
		HashMap<String, String> headers = new HashMap<>();
		headers.put("client","ios");
		List<JSONObject> list = new ArrayList<JSONObject>();
		try {
			String result = HttpUtils.sendGet(url, null,headers);
			JSONObject resultJson = JSONObject.fromObject(result);
			JSONObject data = resultJson.optJSONObject("data");
			JSONArray userBadges = data.optJSONArray("user_badge");
			for (int i = 0; i < userBadges.size(); i++) {
				JSONObject userBadge = userBadges.getJSONObject(i);
				int lv = userBadge.optInt("bl");
				String name = userBadge.optString("bn");
				String owner = userBadge.optString("owner_name");
				JSONObject json = new JSONObject();
				json.put("lv",lv);
				json.put("name",name);
				json.put("owner",owner);
				list.add(json);
			}
		} catch (Exception e) {
			log.error("粉丝牌获取失败: "+e.getMessage(),e);
		}
		return list;
	}

	//根据名字查找用户
	public List<Auth> findAuthListByName(String name){
		return authDao.selectByLikeName(name);
	}

	public Auth findAuthByName(String name){
		return authDao.selectByName(name);
	}

	public List<String> getAuthOldName(int authId){
	    return authOldNameDao.selectAuthOldName(authId);
    }
	
	//根据用户名获取用户发言
	public List<JSONObject> getAuthTalk(String name,boolean fuzzy){
		List<JSONObject> result = new ArrayList<JSONObject>();
		if (StringUtils.isBlank(name)){
			return result;
		}
		if(fuzzy){
			List<Auth> authList = authDao.selectByLikeName(name);
			for (Auth auth : authList) {
				List<JSONObject> list = this.getAuthTalk(auth.getId());
				if(result.isEmpty()){
					for (JSONObject jsonObject : list) {
						jsonObject.put("name", auth.getName());
						jsonObject.put("id", auth.getId());
						result.add(jsonObject);
					}
				} else {
					int index = 0;
					for (JSONObject jsonObject : list) {
						jsonObject.put("name", auth.getName());
						jsonObject.put("id", auth.getId());
						for (int i = index; i < result.size(); i++) {
							index++;
							if (result.get(i).getLong("time") < jsonObject.getLong("time")){
								result.add(i, jsonObject);
								break;
							}
						}
						if (index == result.size()){
							result.add(jsonObject);
							index++;
						}
					}
				}
			}
		} else {
			Auth auth = authDao.selectByName(name);
			if (auth != null){
				result = this.getAuthTalk(auth.getId());
				for (JSONObject jsonObject : result) {
					jsonObject.put("name", auth.getName());
					jsonObject.put("id", auth.getId());
				}
			}
		}
		return result;
	}
	
	
	

	//获取缓存用户
	public Auth getCacheAuth(int id){
		String key = AUTH_KEY + id;
		Auth auth = redisService.get(key, Auth.class);
		if (auth == null){
			auth = this.getAuth(id);
		}
		return auth;
	}
	
	//获取、刷新用户
	private Auth getAuth(int id){
		String key = AUTH_KEY + id;
		Auth auth = this.authDao.selectById(id);
		getAuthOldName(auth);
		if (auth != null){
			redisService.set(key, auth, 6, TimeUnit.HOURS);
		}
		return auth;
	}

	public void reloadAll(){
		Set<String> keys = redisService.keys(AUTH_KEY + "*");
		redisService.del(keys);
	}

	private void getAuthOldName(Auth auth){
		if (auth != null){
			List<String> list = authOldNameDao.selectAuthOldName(auth.getId());
			if (list.isEmpty()){
				auth.setOldName("");
			} else {
				auth.setOldName(list.get(0));
			}
			auth.setOldNameList(list);
		}
	}
	
	public void addAuth(Auth auth){
		authDao.insertAuth(auth);
		this.getAuth(auth.getId());
	}
	
	
	public Auth updateAuthLv(int lv,int id){
		Auth auth = new Auth();
		auth.setId(id);
		auth.setLv(lv);
		this.authDao.updateAuthLv(auth);
		return this.getAuth(id);
	}
	
	public Auth updateAuthName(String name,int id){
		Auth auth = this.getCacheAuth(id);
		this.authOldNameDao.insertAuthOldName(auth.getName(), id);
		auth.setName(name);
		this.authDao.updateAuthName(auth);
		return this.getAuth(id);
	}
	
	public Auth updateAuthIcon(String icon,int id){
		Auth auth = new Auth();
		auth.setId(id);
		auth.setIcon(icon);
		this.authDao.updateAuthIcon(auth);
		return this.getAuth(id);
	}
	
	public Auth updateAuthority(int authority,int id){
		Auth auth = new Auth();
		auth.setId(id);
		auth.setAuthority(authority);
		this.authDao.updateAuthority(auth);
		return this.getAuth(id);
	}
	
	public Auth updateAuthFansLv(int fansLv,int id){
		Auth auth = new Auth();
		auth.setId(id);
		auth.setFansLv(fansLv);
		this.authDao.updateAuthFansLv(auth);
		return this.getAuth(id);
	}
	public Auth updateAuthGuizu(int guizu,int id){
		Auth auth = new Auth();
		auth.setId(id);
		auth.setGuizu(guizu);
		this.authDao.updateAuthGuizu(auth);
		return this.getAuth(id);
	}

	public Auth updateAuthScore(int score,int id){
		Auth auth = new Auth();
		auth.setId(id);
		auth.setScore(score);
		this.authDao.updateAuthScore(auth);
		return this.getAuth(id);
	}


	public JSONObject getAuthLastTalk(int id){
		String key = AUTH_TALK_KEY + id;
		return redisService.rangListOne(key, JSONObject.class);
	}

	public List<JSONObject> getAuthTalk(int id){
		String key = AUTH_TALK_KEY + id;
		List<JSONObject> list = redisService.rangList(key, JSONObject.class);
		return list;
	}
//	private Pattern pattern = Pattern.compile("\\[emot:(dy\\d{3})\\]");
//	public List<JSONObject> getAuthTalkHtml(int id){
//		List<JSONObject> list = this.getAuthTalk(id);
//		for (JSONObject jsonObject : list) {
//			String txt = jsonObject.optString("txt","");
//			txt = pattern.matcher(txt).replaceAll("<img src=\"https://shark.douyucdn.cn/app/douyu/res/page/room-normal/face/$1.png?v=20170626\">");
//			jsonObject.put("txt", txt);
//		}
//		return list;
//	}
	
	
	
	public void setAuthTalk(int id,String txt){
		String key = AUTH_TALK_KEY + id;
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("time",System.currentTimeMillis());
		jsonObject.put("txt",txt);
		redisService.setList(key,jsonObject);
	}
	
	@Scheduled(cron="0 0 4 * * *")
	public void authTalkTask(){
		log.info("clear auth talk");
		Set<String> keys = redisService.keys(AUTH_TALK_KEY + "*");
		long tt = DateUtils.addMonths(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH), -1).getTime();
		for (String key : keys) {
			List<JSONObject> list = redisService.rangList(key, JSONObject.class);
			int index = -1;
			for (JSONObject jsonObject : list) {
				if (jsonObject.getLong("time") > tt){
					index++;
				} else {
					break;
				}
			}
			if (index == -1) {
				redisService.del(key);
			} else {
				redisService.trimList(key,0,index);
			}
		}
	}
	
	
	

}
